"use client"
import React, { useEffect, useState } from "react";
import {
    Button,
    Checkbox,
    CheckboxChangeEvent,
    Col,
    Form,
    Input,
    InputNumber,
    message,
    Modal,
    Radio,
    Row,
    Select,
    Space,
    Tooltip, Tree,
} from 'antd';
import { setTreeSelect } from "@/utils/Z";

import styles from "./index.module.css";
import { QuestionCircleOutlined } from "@ant-design/icons";
import { addRole, getRole, updateRole } from "@/clientApi/system/role";
import {
    roleMenuTreeSelect,
    treeselect as menuTreeSelect
} from "@/clientApi/system/menu";
import { globalMessage } from "@/utils/message";
import { addJob, getJob, updateJob } from "@/clientApi/monitor/job";
import CrontabView from "@/components/Crontab/inedx";

// 定义组件的 props 类型
interface MyComponentProps {
    open: boolean;
    title?: string;
    OnCanCle: () => void;
    jobId?: string;

}

const EditorJobView: React.FC<MyComponentProps> = (props) => {
    const [form] = Form.useForm();
    // 表单的值
    const [formData, setFormData] = useState<any>({})
    const [openCrontab, setOpenCrontab] = useState<boolean>(false)


    function handleCancel() {
        props.OnCanCle()
    }

    useEffect(() => {
        if (props.jobId) {
            getJobForm(props.jobId)
        } else {
            form.setFieldsValue({
                jobName: '',
                jobGroup: '',
                invokeTarget: '',
                cronExpression: '',
                misfirePolicy: '1',
                concurrent: '1',
                status: '0',
            });
        }
    }, [props.jobId]);
    const getJobForm = (id: string): void => {
        getJob(id).then((res: any) => {
            if (res?.code === 200) {
                setFormData(res.data)
                form.setFieldsValue({
                    jobName: res.data?.jobName || '',
                    jobGroup: res.data?.jobGroup || '',
                    invokeTarget: res.data?.invokeTarget || '',
                    cronExpression: res.data?.cronExpression || "",
                    misfirePolicy: res.data?.misfirePolicy || '1',
                    concurrent: res.data?.concurrent || '1',
                    status: res.data?.status || '0'
                });
            }
        });
    };

    const onValuesChange = (changedValues: any, allValues: any) => {
        if (props.jobId !== undefined) {
            setFormData((prevState: any) => ({
                ...prevState, ...changedValues
            }));
        } else {
            setFormData((prevState: any) => ({
                ...allValues
            }));
        }
    };
    const handCheckCrontab = (cronExpression: any) => {
        console.log("cronExpression", cronExpression)

        setFormData((prevState: any) => ({
            ...prevState, cronExpression
        }));
        form.setFieldsValue({
            cronExpression: cronExpression,
        });
        setOpenCrontab(false);
    };
    const handleSubmit = () => {
        // 在提交前先进行表单验证
        form.validateFields().then((values: any) => {
            setFormData((prevState: any) => ({
                ...prevState,
                ...values
            }));
            if (props.jobId !== undefined) {
                updateJob({ ...formData, ...values }).then((res: any) => {
                    globalMessage().warning(res.msg).then(r => { })
                    props.OnCanCle()
                });
            } else {
                addJob({ ...formData, ...values }).then((res: any) => {
                    globalMessage().warning(res.msg).then(r => { })
                    props.OnCanCle()
                });
            }
        }).catch(errorInfo => {

            // 如果验证失败，则不执行提交操作
        });
    }





    return (
        <>
            <Modal
                forceRender
                open={props.open}
                title={props.title}
                footer={null}
                onCancel={() => {
                    props.OnCanCle()
                }}
                width={800}
            >
                <Form
                    form={form}
                    name="editorrole"
                    onValuesChange={onValuesChange}
                    style={{ maxWidth: 800 }}
                >
                    <Row gutter={10}>
                        <Col span={12}>
                            <Form.Item
                                labelCol={{ span: 6, }}
                                label="任务名称"
                                name="jobName"
                                rules={[{ required: true, message: "任务名称不能为空", }]}
                            >
                                <Input />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                labelCol={{ span: 6, }}
                                label={<Tooltip
                                    title="任务分组"><QuestionCircleOutlined />任务分组</Tooltip>}
                                name="jobGroup"
                                rules={[{ required: true, message: "任务分组不能为空" }]}
                            >
                                <Select
                                    style={{ width: "100%" }}
                                    options={[{ value: 'DEFAULT', label: '默认' }, { value: 'SYSTEM', label: '系统' }]}></Select>
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={10}>
                        <Col span={12}>
                            <Form.Item
                                labelCol={{ span: 6, }}
                                label={<Tooltip
                                    title="Bean调用示例：ryTask.ryParams('ry')
Class类调用示例：com.ruoyi.quartz.task.RyTask.ryParams('ry')
参数说明：支持字符串，布尔类型，长整型，浮点型，整型"><QuestionCircleOutlined />调用方法</Tooltip>}
                                name="invokeTarget"
                                rules={[{ required: true, message: "调用方法不能为空" }]}
                            >
                                <Input />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={10}>
                        <Col span={24}>
                            <Form.Item
                                labelCol={{ span: 3, }}
                                label="cron表达式"
                                name="cronExpression"
                                rules={[{ required: true, message: "cron表达式不能为空" }]}
                            >
                                <Space.Compact style={{ width: '100%' }}>
                                    <Input value={formData.cronExpression || ''} />
                                    <Button type="primary" onClick={() => setOpenCrontab(true)} >创建表达式</Button>
                                </Space.Compact>
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={10}>
                        <Col span={24}>
                            <Form.Item
                                labelCol={{ span: 3, }}
                                label="执行策略"
                                name="misfirePolicy"
                            >
                                <Radio.Group>
                                    <Radio.Button value={"1"}>立即执行</Radio.Button>
                                    <Radio.Button value={"2"}>执行一次</Radio.Button>
                                    <Radio.Button value={"3"}>放弃执行</Radio.Button>
                                </Radio.Group>
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={10}>
                        <Col span={12}>
                            <Form.Item
                                labelCol={{ span: 6, }}
                                label="是否并发"
                                name="concurrent"
                            >
                                <Radio.Group>
                                    <Radio.Button value={"0"}>允许</Radio.Button>
                                    <Radio.Button value={"1"}>禁止</Radio.Button>
                                </Radio.Group>
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                labelCol={{ span: 6, }}
                                label="状态"
                                name="status"
                            >
                                <Radio.Group>
                                    <Radio value={"0"}>正常</Radio>
                                    <Radio value={"1"}>暂停</Radio>
                                </Radio.Group>
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={10}>
                        <Col span={24}>
                            <Form.Item
                                wrapperCol={{ offset: 16, span: 8 }}
                            >
                                <div className={styles.buttonClass}>
                                    <Button type="primary" htmlType="submit" onClick={handleSubmit}>确认</Button>
                                    <Button type="primary" onClick={handleCancel}>取消</Button>
                                </div>
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </Modal>
            {openCrontab && <CrontabView cronValue={formData.cronExpression} title={"表达式"} open={openCrontab} onOk={(e) => handCheckCrontab(e)}
                OnCanCle={() => {
                    setOpenCrontab(false);

                }} />}
        </>
    )
};
export default EditorJobView;
